package com.bzy.common.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;


public class CommonsUtils {
	
	public static final String sexCodePrefix = "7070760"; 
	


	public static Long enlargeLocation(Double location) {
		return (long) (location * 1000000L);
	}

	public static Long enlargeLocation(Double location, Long enlarge) {
		if (enlarge == null) {
			enlarge = 1000000L;
		}

		if (location == null) {
			return null;
		}

		return (long) (location * enlarge);
	}


	/**
	 * 产生令牌
	 * 
	 * @return
	 */
	public static String genAccessToken() {
		return UUID.randomUUID().toString();
	}

	public static boolean matchUrlPrefix(String orgUrl, List<String> matchUrls) {
		return matchUrlPrefix(orgUrl, matchUrls, 0);
	}

	/**
	 * 
	 * @param orgUrl
	 * @param matchUrls
	 * @param matchType
	 *            0 --- 前缀匹配 1 --- 包含 2 --- 后缀匹配
	 * @return
	 */
	public static boolean matchUrlPrefix(String orgUrl, List<String> matchUrls, int matchType) {

		if (StringUtils.isEmpty(orgUrl)) {
			return false;
		}

		boolean match = false;
		if (matchUrls != null) {
			for (String url : matchUrls) {
				if (matchUrlPrefix(orgUrl, url, matchType)) {
					return true;
				}
			}
		}

		return match;
	}

	public static boolean matchUrlPrefix(String orgUrl, String matchUrl) {
		return matchUrlPrefix(orgUrl, matchUrl, 0);
	}

	public static boolean matchUrlPrefix(String orgUrl, String matchUrl, int matchType) {

		if (StringUtils.isEmpty(orgUrl)) {
			return false;
		}

		boolean match = false;

		if (matchUrl != null) {
			switch (matchType) {
			case 0:
				if (orgUrl.startsWith(matchUrl)) {
					return true;
				}
				break;
			case 1:
				if (orgUrl.contains(matchUrl)) {
					return true;
				}
				break;

			case 2:
				if (orgUrl.endsWith(matchUrl)) {
					return true;
				}
				break;
			}
		}

		return match;
	}

	/**
	 * 返回uuid字符串
	 */
	public static String getUUID() {
		return UUID.randomUUID().toString();
	}

	public static String getUserUid() {
		int uuuid = new Random().nextInt(999999999);
		return String.valueOf(uuuid);
	}

	/**
	 * 返回订单编号
	 */
	public static String getOrderNum() {
		int r1 = (int) (Math.random() * (10));// 产生2个0-9的随机数
		int r2 = (int) (Math.random() * (10));
		// int r3=(int)(Math.random()*(10));
		// int r4=(int)(Math.random()*(10));
		long now = System.currentTimeMillis();// 一个13位的时间戳
		System.out.println("System.currentTimeMillis : " + now);
		String paymentID = String.valueOf(now) + String.valueOf(r1) + String.valueOf(r2);// 订单ID
		if (paymentID.length() > 15) {
			paymentID = paymentID.substring(0, 15);
		}
		System.out.println("paymentID : " + paymentID);
		return paymentID;
	}

	/**
	 * 返回uuid做主键 不带 ' - '
	 * 
	 * @return
	 */
	public static String getNoLineUId() {
		String s = UUID.randomUUID().toString();
		return s.substring(0, 8) + s.substring(9, 13) + s.substring(19, 23) + s.substring(24);
	}

	/**
	 * 时间戳
	 */
	public static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}

	/**
	 * 返回订单号
	 */
	public static String getOrderCode() {
		long date = System.currentTimeMillis();
		int random = (int) (Math.random() * 1000000);
		String orderCode = "HFNM" + random + date;
		return orderCode;
	}

	/**
	 * 获取文件后缀名
	 * 
	 * @param filename
	 * @return
	 */
	public static String getFileSuffix(String filename) {

		if (filename == null || filename.trim().equals("")) {
			return "";
		}

		String[] sf = filename.split("\\.");
		if (sf.length > 1) {
			return sf[sf.length - 1];
		}

		return "";
	}

	/**
	 * 获取当前端口
	 * 
	 */
	public static String getServerUrl(HttpServletRequest request) {
		String SERVER_URL = null;
		String host = request.getLocalAddr();
		String outHost = "115.28.180.99";
		String port = request.getLocalPort() + "";
		String contextPath = request.getContextPath();

		if (SERVER_URL == null) {
			SERVER_URL = String.format("http://%s:%s/%s/", host, port, contextPath);
			// SERVER_RUL = String.format("http://%s:%s/%s/",
			// outHost,port,contextPath);
			// System.out.println(" SERVER_URL : "+SERVER_URL);
		}
		return SERVER_URL;
	}

	/**
	 * 递归删除目录下的所有文件及子目录下所有文件
	 * 
	 * @param dir
	 *            将要删除的文件目录
	 * @return
	 */
	public static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}
		// 目录为空可删除
		return dir.delete();
	}

	/**
	 * 验证邮箱
	 * 
	 * @param email
	 * @return
	 */
	public static boolean checkEmail(String email) {
		boolean flag = false;
		try {
			String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
			Pattern regex = Pattern.compile(check);
			Matcher matcher = regex.matcher(email);
			flag = matcher.matches();
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}

	/**
	 * 对象转换为map
	 * 
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> objectToMap(Object obj) throws Exception {
		if (obj == null)
			return null;
		Map<String, Object> map = new HashMap<String, Object>();
		BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
		for (PropertyDescriptor property : propertyDescriptors) {
			String key = property.getName();
			if (key.compareToIgnoreCase("class") == 0) {
				continue;
			}
			Method getter = property.getReadMethod();
			Object value = getter != null ? getter.invoke(obj) : null;
			map.put(key, value);
		}
		return map;
	}

	@SuppressWarnings("unchecked")
	public static boolean isBaseType(Class clazz) {
		if (clazz == null) {
			return false;
		}
		String className = clazz.getName().toLowerCase();
		if (className.startsWith("java.")) {
			return true;
		} else {
			return false;
		}
	}


	/**
	 * 随机生成6位数的验证码
	 * 
	 * @return
	 */
	public static String createRandomVcode() {
		// 验证码
		String vcode = "";
		for (int i = 0; i < 6; i++) {
			vcode = vcode + (int) (Math.random() * 9);
		}
		return vcode;
	}

	public static Object[] getStartAndEndTime(Integer day) {
		Object[] objects = new Object[2];

		Date now = new Date();
		String nowString = DateUtils.toDateString(now, DateUtils.ISO_DATE_FORMATTER);
		switch (day) {
		case 1:
			objects[0] = nowString + " 00:00:00";
			objects[1] = nowString + " 23:59:59";
			break;
		case 3:
			long three = Math.abs((long) (3 * 24 * 60 * 60 * 1000));
			long threeEndLong = now.getTime() - three;
			Date threeEndDate = new Date(threeEndLong);
			String threeEndString = DateUtils.toDateString(threeEndDate, DateUtils.ISO_DATE_FORMATTER);
			objects[0] = threeEndString + " 00:00:00";
			objects[1] = nowString + " 23:59:59";
			break;
		case 7:
			long seven = Math.abs((long) (7 * 24 * 60 * 60 * 1000));
			long sevenEndLong = now.getTime() - seven;
			Date sevenEndDate = new Date(sevenEndLong);
			String sevenEndString = DateUtils.toDateString(sevenEndDate, DateUtils.ISO_DATE_FORMATTER);
			objects[0] = sevenEndString + " 00:00:00";
			objects[1] = nowString + " 23:59:59";
			break;
		default:
			break;
		}
		return objects;
	}

	/**
	 * 获取小数
	 * 
	 * @param d
	 * @param num
	 * @return
	 */
	public static double decimalPoint(double d, int num) {
		BigDecimal bd = new BigDecimal(d);
		return bd.setScale(num, RoundingMode.DOWN).doubleValue();
	}



	public static int keepSignSevenOrMonth(int keepSignNum) {
		if ((keepSignNum / 30) >= 1 && (keepSignNum % 30 == 0)) {
			return 30;
		}
		if ((keepSignNum / 7) >= 1 && (keepSignNum % 7 == 0)) {
			return 7;
		}
		return 0;
	}

	/*
	 * List<Integer>转化List<String>
	 */
	public static List<String> IntegerToStringLst(List<Integer> inList) {
		if (inList == null) {
			return null;
		}
		List<String> iList = new ArrayList<String>(inList.size());
		try {
			for (int i = 0, j = inList.size(); i < j; i++) {
				iList.add(String.valueOf(inList.get(i)));
			}
		} catch (Exception e) {
		}
		return iList;
	}

	/**
	 * 创建UUID
	 * 
	 * @return
	 */
	public static synchronized String makeUUID() {
		String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
		return uuid;
	}



	/**
	 * 随机字符串
	 */
	public static String create_nonce_str() {
		return UUID.randomUUID().toString();
	}

	/**
	 * 把中文转成Unicode码
	 * 
	 * @param str
	 * @return
	 */
	public static String chinaToUnicode(String str) {
		String result = "";
		for (int i = 0; i < str.length(); i++) {
			int chr1 = (char) str.charAt(i);
			if (chr1 >= 19968 && chr1 <= 171941) {// 汉字范围 \u4e00-\u9fa5 (中文)
				result += "\\u" + Integer.toHexString(chr1);
			} else {
				result += str.charAt(i);
			}
		}
		return result;
	}

	/**
	 * 替换四个字节的字符 '\xF0\x9F\x98\x84\xF0\x9F）的解决方案 😁
	 * 
	 * @author zhuyong
	 * @param content
	 * @return
	 */
	public static String removeFourChar(String content) {
		byte[] conbyte = content.getBytes();
		for (int i = 0; i < conbyte.length; i++) {
			if ((conbyte[i] & 0xF8) == 0xF0) {
				for (int j = 0; j < 4; j++) {
					conbyte[i + j] = 0x30;
				}
				i += 3;
			}
		}
		content = new String(conbyte);
		return content.replaceAll("0000", "");
	}

	public static final int STATUS_1 = 0x01;
	public static final int STATUS_2 = 0x02;
	public static final int STATUS_3 = 0x04;
	public static final int STATUS_4 = 0x08;

	public static void main(String[] args) throws ClassNotFoundException {

		BigDecimal aLong = new BigDecimal(9L).divide(new BigDecimal(16L));
		aLong = aLong.multiply(new BigDecimal(100));
		System.out.println(aLong.intValue());
	}

	// public void get

	public static boolean isInteger(String str) {
		Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
		return pattern.matcher(str).matches();
	}


}
